package dnl.util.ui;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;

/**
 * 
 * @author daniel
 */
public class PopupUtils {

	public static void addPopup(Component c, final JPopupMenu popupMenu) {
		c.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				// on some operating systems only one of the following
				// conditions works
				if (e.isPopupTrigger() || SwingUtilities.isRightMouseButton(e)) {
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});
	}

	public static void addPopup(final JTree tree, final JPopupMenu popupMenu) {
		tree.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					TreePath selPath = tree.getClosestPathForLocation(e.getX(), e.getY());
					tree.setSelectionPath(selPath);
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});
	}

	public static void addPopup(final JTable jTable, final JPopupMenu popupMenu) {

		jTable.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				jTable.requestFocus();
				final int row = jTable.rowAtPoint(e.getPoint());
				if (row < 0)
					return;
				if (SwingUtilities.isRightMouseButton(e)) {
					jTable.setRowSelectionInterval(row, row);
					popupMenu.show(jTable, e.getX(), e.getY());
				}
			}
		});
	}
}
